﻿/*
   Copyright 2013 Dmitry Bratus

   Licensed under the Apache License, Version 2.0 (the "License");
   you may not use this file except in compliance with the License.
   You may obtain a copy of the License at

       http://www.apache.org/licenses/LICENSE-2.0

   Unless required by applicable law or agreed to in writing, software
   distributed under the License is distributed on an "AS IS" BASIS,
   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
   See the License for the specific language governing permissions and
   limitations under the License.
*/
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Flower.Services;
using Flower.Services.Data;
using Flower.Client;
using Flower.Logging;
using System.Threading;
using System.Configuration;
using System.Data.SqlClient;
using Flower.Directory.Util;
using System.Threading.Tasks;

namespace Flower.SqlServer.QueueService
{
    public class QueueService : IQueueService
    {
        private static readonly Log Log = LogManager.CreateLog(typeof(QueueService).Name);

        private const string ResourcePrefix = "QUEUE_";

        private readonly IFlowerClient _flowerClient;
        private readonly string _connectionString;

        public QueueService(IFlowerClient flowerClient, string connectionStringName)
        {
            _flowerClient = flowerClient;

            ConnectionStringSettings connStrSettings =
                ConfigurationManager.ConnectionStrings[connectionStringName];

            if (connStrSettings == null)
            {
                throw new InvalidOperationException(string.Format("Connection string '{0}' is not found.", connectionStringName));
            }

            _connectionString = connStrSettings.ConnectionString;
        }

        public Guid Enqueue(string recipient, Blob message)
        {
            if (recipient == null) throw new ArgumentNullException("recipient");
            if (message == null || message.Data == null) throw new ArgumentNullException("message");

            DemandLock.Acquire(ResourcePrefix + recipient, null, null, ex => Log.Error("Lock failure.", ex));

            var id = Guid.NewGuid();

            using (var connection = new SqlConnection(_connectionString))
            {
                connection.Open();

                using (var cmd = new SqlCommandBuilder(connection))
                {
                    string waiterId = 
                        cmd
                            .SetText("dbo.Enqueue")
                            .AddParameter("@Id", id)
                            .AddParameter("@Recipient", recipient)
                            .AddParameter("@Data", message.Data)
                            .AddParameter("@DataFormat", (int)message.Format)
                            .ExecuteString();

                    if (waiterId != null)
                    {
                        _flowerClient
                            .CreateScript()
                            .SetText("@ChangeProcessStatus")
                            .AddParameter("pid", waiterId)
                            .AddParameter("status", "Pending")
                            .Execute();
                    }
                }
            }

            return id;
        }

        public Blob Dequeue(string recipient, string waiterId)
        {
            if (recipient == null) throw new ArgumentNullException("recipient");
            if (waiterId == null) throw new ArgumentNullException("waiterId");

            DemandLock.Acquire(ResourcePrefix + recipient, null, null, ex => Log.Error("Lock failure.", ex));

            using (var connection = new SqlConnection(_connectionString))
            {
                connection.Open();

                using (var cmd = new SqlCommandBuilder(connection))
                {
                    Blob message =
                        cmd
                            .SetText("dbo.Dequeue")
                            .AddParameter("@Recipient", recipient)
                            .AddParameter("@WaiterId", waiterId)
                            .ExecuteSingleRow
                            (
                                reader =>
                                    new Blob
                                    {
                                        Data = (byte[])reader["Data"],
                                        Format = (BlobFormat)(int)reader["DataFormat"]
                                    }
                            );

                    if (message == null)
                    {
                        _flowerClient
                            .CreateScript()
                            .SetText("@ChangeProcessStatus")
                            .AddParameter("pid", waiterId)
                            .AddParameter("status", "Waiting")
                            .Execute();
                    }

                    return message;
                }
            }
        }

        public IList<string> GetRecipients(long start, long limit)
        {
            using (var connection = new SqlConnection(_connectionString))
            {
                connection.Open();

                using (var cmd = new SqlCommandBuilder(connection))
                {
                    return 
                        cmd
                            .SetText("dbo.GetRecipients")
                            .AddParameter("@Start", start)
                            .AddParameter("@Limit", limit)
                            .ExecuteReader(reader => (string)reader["Recipient"])
                            .ToList();
                }
            }
        }

        private static QueueServiceMessage MapQueueServiceMessage(SqlDataReader reader)
        {
            return
                new QueueServiceMessage 
                {
                    Id = (Guid)reader["Id"],
                    Data = new Blob 
                    {
                        Data = (byte[])reader["Data"],
                        Format = (BlobFormat)(int)reader["DataFormat"]
                    },
                    PutOn = (DateTime)reader["PutOn"],
                    Recipient = (string)reader["Recipient"]
                };
        }

        public IList<QueueServiceMessage> GetMessagesById(IList<Guid> ids)
        {
            if (ids == null) throw new ArgumentNullException("ids");

            using (var connection = new SqlConnection(_connectionString))
            {
                connection.Open();

                using (var cmd = new SqlCommandBuilder(connection))
                {
                    return
                        cmd
                            .SetText("dbo.GetMessagesById")
                            .AddParameter("@Ids", ids)
                            .ExecuteReader(MapQueueServiceMessage)
                            .ToList();
                }
            }
        }

        public IList<QueueServiceMessage> GetMessagesByRecipient(IList<string> recipients, DateTime? start, DateTime? end)
        {
            using (var connection = new SqlConnection(_connectionString))
            {
                connection.Open();

                using (var cmd = new SqlCommandBuilder(connection))
                {
                    return
                        cmd
                            .SetText("dbo.GetMessagesByRecipient")
                            .AddParameter("@Recipients", recipients ?? new List<string>())
                            .AddParameter("@Start", start)
                            .AddParameter("@End", end)
                            .ExecuteReader(MapQueueServiceMessage)
                            .ToList();
                }
            }
        }

        public IList<Recipient> ExportRecipients(IList<string> recipients)
        {
            if (recipients == null) throw new ArgumentNullException("recipients");

            var messages = new List<QueueServiceMessage>();
            var waiters = new Dictionary<string, List<string>>();
            
            using (var connection = new SqlConnection(_connectionString))
            {
                connection.Open();

                using (var cmd = new SqlCommandBuilder(connection))
                {
                    messages.AddRange
                    (
                        cmd
                            .SetText("dbo.GetMessagesByRecipient")
                            .AddParameter("@Recipients", recipients)
                            .AddParameter("@Start", (DateTime?)null)
                            .AddParameter("@End", (DateTime?)null)
                            .ExecuteReader(MapQueueServiceMessage)
                    );
                }

                using (var cmd = new SqlCommandBuilder(connection))
                {
                    cmd
                        .SetText("dbo.GetWaitersByRecipient")
                        .AddParameter("@Recipients", recipients)
                        .ExecuteReaderWithAction
                        (
                            reader =>
                            {
                                var waiterId = (string)reader["WaiterId"];
                                var recipient = (string)reader["Recipient"];

                                List<string> waitersOfRecipient;

                                if (!waiters.TryGetValue(recipient, out waitersOfRecipient))
                                {
                                    waitersOfRecipient = new List<string>();
                                    waiters.Add(recipient, waitersOfRecipient);
                                }

                                waitersOfRecipient.Add(waiterId);
                            }
                        );
                }
            }

            var result = new List<Recipient>
            (
                messages
                    .GroupBy(msg => msg.Recipient)
                    .Select
                    (
                        msgGroup => 
                        {
                            List<string> waitersOfRecipient;

                            if (waiters.TryGetValue(msgGroup.Key, out waitersOfRecipient))
                            {
                                waiters.Remove(msgGroup.Key);
                            }
                            else
                            {
                                waitersOfRecipient = new List<string>();
                            }

                            return new Recipient 
                            {
                                Id = msgGroup.Key,
                                Messages = msgGroup.ToList(),
                                Waiters = waitersOfRecipient
                            };
                        }
                    )
            );

            result.AddRange
            (
                waiters
                    .Select
                    (
                        kv => new Recipient 
                        {
                            Id = kv.Key,
                            Messages = new List<QueueServiceMessage>(),
                            Waiters = kv.Value
                        }
                    )
            );

            return result;
        }

        public void ImportRecipients(IList<Recipient> recipients)
        {
            using (var connection = new SqlConnection(_connectionString))
            {
                connection.Open();

                using (var cmd = new SqlCommandBuilder(connection))
                {
                    cmd
                        .SetText("dbo.ImportRecipients")
                        .AddParameter
                        (
                            "@Messages", 
                            bld => 
                                bld
                                    .Column<Guid>("Id")
                                    .Column<string>("Recipient")
                                    .Column<byte[]>("Data")
                                    .Column<int>("DataFormat")
                                    .Column<DateTime>("PutOn")
                                    .Rows
                                    (
                                        recipients.SelectMany(rcp => rcp.Messages), 
                                        msg => msg.Id,
                                        msg => msg.Recipient,
                                        msg => msg.Data.Data,
                                        msg => msg.Data.Format,
                                        msg => msg.PutOn
                                    )
                            ,
                            "TMessageRow"
                        )
                        .AddParameter
                        (
                            "@Waiters", 
                            bld =>
                                bld
                                    .Column<string>("Recipient")
                                    .Column<string>("WaiterId")
                                    .Rows
                                    (
                                        recipients
                                            .SelectMany
                                            (
                                                rcp => 
                                                    rcp
                                                        .Waiters
                                                        .Select
                                                        (
                                                            w => new
                                                            {
                                                                Recipient = rcp.Id,
                                                                WaiterId = w
                                                            }
                                                        )
                                            ),
                                        waiter => waiter.Recipient,
                                        waiter => waiter.WaiterId
                                    )
                            ,
                            "TWaiterRow"
                        )
                        .Execute();
                }
            }
        }

        public void RemoveMessages(IList<Guid> ids)
        {
            using (var connection = new SqlConnection(_connectionString))
            {
                connection.Open();

                using (var cmd = new SqlCommandBuilder(connection))
                {
                    cmd
                        .SetText("dbo.RemoveMessages")
                        .AddParameter("@Ids", ids)
                        .Execute();
                }
            }
        }

        public void RemoveRecipients(IList<string> recipients)
        {
            using (var connection = new SqlConnection(_connectionString))
            {
                connection.Open();

                using (var cmd = new SqlCommandBuilder(connection))
                {
                    cmd
                        .SetText("dbo.RemoveRecipients")
                        .AddParameter("@Recipients", recipients)
                        .Execute();
                }
            }
        }
    }
}
